package cn.texous.web.parsing.book.controller;

import cn.texous.util.commons.constant.Result;
import cn.texous.web.parsing.book.context.OriginParserContext;
import cn.texous.web.parsing.book.manager.OriginManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 书源管理
 * 1. 书源导入：结合文件上传功能
 * 2. 刷新书源， 需要改造：可单独刷新单个书源
 * TODO 3. 兼容，爱阅书香书源，阅读书源
 *
 * @author Showa.L
 * @since 2019/5/9 20:15
 */
@Slf4j
@RestController
@RequestMapping("/origin")
@Api(value = "/origin", tags = "数据源管理")
public class OriginManagerController {

    @Autowired
    private OriginManager originManager;
    @Autowired
    private OriginParserContext originParserContext;

    @GetMapping("/refresh")
    @ApiOperation("刷新书源")
    public Result<Boolean> originRefresh() {
        originParserContext.init();
        return Result.ok(true);
    }

    /*
     *采用spring提供的上传文件的方法
     */
    @PostMapping(value = "/files")
    @ResponseBody
    @ApiOperation(value = "导入书源（文件导入）")
    public Result<List<String>> springUpload(HttpServletRequest request)
            throws IllegalStateException, IOException {
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        List<String> fileUrls = new ArrayList<>();
        //检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                //一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if (file != null) {
                    try (InputStream inputStream = file.getInputStream();
                         InputStreamReader reader = new InputStreamReader(inputStream);
                         BufferedReader br = new BufferedReader(reader)) {
                        String line = null;
                        StringBuilder sb = new StringBuilder();
                        while ((line = br.readLine()) != null) {
                            sb.append(line);
                        }
                        if (sb.charAt(0) == '{') {
                            sb.append("]");
                            sb.insert(0, "[");
                        }
                        if (sb.length() > 0)
                            originManager.parseOrigins(sb.toString());
                    }
                }
            }
        }
        return Result.ok(fileUrls);
    }

    @PostMapping("/jsons")
    @ApiOperation("导入书源（JSON list 导入）")
    public Result<Boolean> originStore(@RequestBody String origins) {
        if (origins != null && origins.startsWith("{"))
            origins = "[" + origins + "]";

        return Result.ok(originManager.parseOrigins(origins));
    }


}
